package com.bxw.forum.controller;


import com.bxw.forum.common.AppResult;
import com.bxw.forum.common.ResultCode;
import com.bxw.forum.model.Article;
import com.bxw.forum.model.ArticleReply;
import com.bxw.forum.model.User;
import com.bxw.forum.service.IArticleReplyService;
import com.bxw.forum.service.IArticleService;
import com.bxw.forum.utils.GetRequest;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Result;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IArticleReplyService articleReplyService;

    @RequestMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @RequestParam(value = "articleId") @NonNull Long articleId,
                            @RequestParam(value = "content") @NonNull String content) {

        User user = GetRequest.getUser(request);

        if(user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        Article article = articleService.selectById(articleId);

        if(article == null || article.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());

            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        if(article.getState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());

            return AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED);
        }

        ArticleReply articleReply = new ArticleReply();
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        articleReply.setArticleId(articleId);

        articleReplyService.create(articleReply);

        return AppResult.success();
    }

    @RequestMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(@RequestParam(value = "articleId") @NonNull Long articleId) {
        // 校验帖子是否存在
        Article article = articleService.selectById(articleId);
        if (article == null || article.getDeleteState() == 1) {
            // 返回错误提示
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 调用Service
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        // 返回结果
        return AppResult.success(articleReplies);
    }
}
